<?php
/**
 * Created by PhpStorm.
 * User: newrain
 * Date: 2017/11/30
 * Time: 14:09
 * State: 产品相关接口
 */

class FundController extends BaseController
{
    private $rules = [
        'fundId' => 'required|int'
    ];

    /**
     * 产品列表接口
     */
    public function listAction()
    {
        $page = $this->getRequest()->getParam('page');
        $type = empty($this->getRequest()->getParam('type'))?1:$this->getRequest()->getParam('type');
        $uId = $this->header['uid'];
        //获取产品列表
        $fund = FundModel::select(['id','fund_name','fund_type','products_size','investment_term','minimum_Money','fund_pwd','status','risk_rank'])
                ->where('type', $type)->where('pattern', '=', 0)->where('status', '<', '2')->orderBy('status', 'asc')
                ->orderBy('update_time', 'desc')->paginate('10', '', 'page', $page);
        $list = $fund->items();
        $data['list'] = FundModel::classifyList($list,$uId);
        $data['page']['lastPage']    = $fund->lastPage();
        $data['page']['perPage']     = $fund->perPage();
        $data['page']['currentPage'] = $fund->currentPage();
        $this->callback($data);
    }

    /**
     *  产品详情接口
     */
    public function detailAction()
    {
        $fundId = $this->getRequest()->getParam('fund_id');
        $uId = $this->header['uid'];
        //验证参数
        $vdata = ['fundId'=>$fundId];
        if (!Rester\Validator::validators($this->rules, $vdata)) {
            $this->callback([], MISS_REQUEST_PARAMS, '参数不正确!');
        }
        //获取产详情
        $fundDetail = FundModel::select('id', 'fund_name', 'fund_type', 'investment_strategy', 'products_size',
            'investment_term', 'minimum_money', 'status', 'risk_rank', 'investment_direction', 'operation_type',
            'pattern', 'raise_deadline', 'subscription_cost', 'add_time')
            ->where('id', $fundId)->first();
        $fundDetail['add_time'] = date('Y-m-d',$fundDetail['add_time']);
        $data['detail'] = $fundDetail;
        //设置alert_url
        $data['detail']['alert_url'] = '';
        $data['detail']['alert_title'] = '';
        $commonconf = getCommonConfig('h5_baseurl');
        //判断用户是否首次查看高风险或者低风险 TODO
        $uriskRank = UserModel::select('high_risk_time', 'low_risk_time')->where('id', $uId)->first();

        if ($fundDetail['risk_rank'] == 5) {
            //判断当前用户是否提示过高风险
            if ($uriskRank['high_risk_time']=="0000-00-00 00:00:00") {
                $data['detail']['alert_url'] = urlencode($commonconf.'/fund/galert');
                $data['detail']['alert_title'] = '高风险产品特别风险揭示';
            }
        } else {
            //判断当前用户是否提示过低风险
            if ($uriskRank['low_risk_time']=="0000-00-00 00:00:00") {
                $data['detail']['alert_url'] = urlencode($commonconf.'/fund/dalert');
                $data['detail']['alert_title'] = '风险揭示书';
            }
        }
        //获取产品公告和基金净值
        $list = FunduploadModel::where(['f_id'=>$fundId,'status'=>0])
            ->orderBy('add_time', 'desc')
            ->get(['id','add_time','file_name','type','img_file_path']);
        //归类
        $classifyList = FunduploadModel::classifyList($list);
        $data['list_notice'] = $classifyList['list_notice'];
        $data['list_net'] = $classifyList['list_net'];


        $data['detail']['fund_risk_level'] = getProductRiskDescription($fundDetail['risk_rank']);

        $score = EvaluationModel::select('evaluation_score')->where('uid', $uId)->first();
        $userlevel = \Service\UserService::getInstance()->getGrade($score['evaluation_score']);
        $data['detail']['user_risk_level'] = getUserRiskDescription($userlevel['grade_int']);
        $data['detail']['pattern'] = $fundDetail['pattern'];

        $this->callback($data);
    }

    public function preclickAction()
    {
        $fundId = $this->getRequest()->getParam('fund_id');
        $uId = $this->header['uid'];
        //验证参数
        $vdata = ['fundId'=>$fundId];
        if (!Rester\Validator::validators($this->rules, $vdata)) {
            $this->callback([], MISS_REQUEST_PARAMS, '参数不正确!');
        }
        if (($check = FundModel::validConsultStatus($fundId)) !== true) {
            $this->callback([], '0400', $check);
            return;
        }

        $return = $this->checkConsultation($fundId);

        $commonconf = getCommonConfig('h5_baseurl');
        $fundDetail = FundModel::query()->find($fundId);
        if ($fundDetail['risk_rank'] == 5) {
            $return['alert_url'] = urlencode($commonconf.'/fund/galert');
            $return['alert_title'] = '高风险产品特别风险揭示';
        } else {
            $return['alert_url'] = urlencode($commonconf.'/fund/dalert');
            $return['alert_title'] = '风险揭示书';
        }
        $this->callback($return);
    }

    protected function checkConsultation($fid)
    {
        $uid = $this->header['uid'];
        /** @var UserModel $user */
        $user = UserModel::query()->find($uid);
        if (!$user) {
            return [];
        }
        $private = UserPrivateModel::findOrCreate($uid, $fid);
        $return = [];
        $return['need_addition_info'] = $user->is_private_fund_status == 1 ? 1 : 0;
        $userMinShi = UserMSModel::query()->where(['user_id' => $uid])->first();
        if (empty($userMinShi) || $userMinShi->status != UserMsModel::STATUS_PASS) {
            $return['need_upload_id_photo'] = 1;
        } else {
            $return['need_upload_id_photo'] = 0;
        }

        if ($private->isOk() && \Service\ConsulationService::hasConsulation($uid, $fid)) {
            $return['is_first'] = 0;
        } else {
            $return['is_first'] = 1;
        }
        $return['verify_fail_limit'] = UserVerifaceRecordModel::getUsedCnt($uid, $fid) >=20 ? 1:0;
        $private->clearFailStatus($return['verify_fail_limit']);
        $return['is_manual_checking'] = $private->isManualChecking();
        if ($record = UserVerifaceRecordModel::getLast($uid, $fid)) {
            $return['last_img'] = getUploadHost() . $record->photo_path;
        } else {
            $return['last_img'] = '';
        }

        if ($return['is_first'] == 1) {
            $return['show_risk_tip_now'] = $private->showRiskTipDirectly();
        } else {
            $return['show_risk_tip_now'] = 0;
        }
        $return['first_edit'] = $user->first_edit;



        return $return;
    }

    /**
     * 提交风险提示接口
     */
    public function confirmRiskAction()
    {
        $fundId = $this->getRequest()->getParam('fund_id');
        $uId = $this->header['uid'];
        //验证参数
        $vdata = ['fundId'=>$fundId];
        if (!Rester\Validator::validators($this->rules, $vdata)) {
            $this->callback([], MISS_REQUEST_PARAMS, '参数不正确!');
        }
        //判断该风险值为高风险还是低风险
        $fundDetail = FundModel::where("id", $fundId)->get(['id','risk_rank'])->first();
        $riskRank = $fundDetail['risk_rank'];
        $userDetail = UserModel::select('id','view_private_product_status')->where('id', $uId)->first();
        if ($riskRank == 5) {
            //执行高风险确认
            if($userDetail['view_private_product_status'])
            {
                $viewhigh = $userDetail['view_private_product_status'].',2';
            }else{
                $viewhigh = '2';
            }
            UserModel::where('id', '=', $uId)->update(array('high_risk_time' => date("Y-m-d H:i:s"),'view_private_product_status'=>$viewhigh));
        } else {
            //执行低风险确认
            if($userDetail['view_private_product_status'])
            {
                $viewlow = $userDetail['view_private_product_status'].',1';
            }else{
                $viewlow = '1';
            }
            UserModel::where('id', '=', $uId)->update(array('low_risk_time' => date("Y-m-d H:i:s"),'view_private_product_status'=>$viewlow));
        }
        $this->callback([]);
    }
}
